//
//  DMErWeiMaViewController.m
//  DMGME
//
//  Created by MC on 15/10/16.
//  Copyright © 2015年 GYP. All rights reserved.
//

#import "DMErWeiMaViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "testController.h"
#import "DMoeferDetailModel.h"
#import "DMOrderDetailCell.h"
#import "UIImageView+WebCache.h"

#import "DMOrderDetail.h"

#define LIGHT_OPAQUE_BLACK_COLOR [UIColor colorWithRed:1.0/255.0 green:1.0/255.0 blue:1.0/255.0 alpha:0.3f]

//********扫描区域********//
#define leftright 50
//
#define Size ([UIScreen mainScreen].bounds.size.width-leftright*2)
//
#define top 150
//**********************//


@interface DMErWeiMaViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>

{
    int num;
    BOOL upOrDown;
    NSTimer *timer;
    UIView *backView;
    
    NSString *_carId;
    NSString *_userId;
    NSString *_activityId;
    NSString *_stringValue;
  
}

@property (strong ,nonatomic ) AVCaptureDevice * device;

@property (strong , nonatomic ) AVCaptureDeviceInput * input;

@property (strong , nonatomic ) AVCaptureMetadataOutput * output;

@property (strong , nonatomic ) AVCaptureSession * session;

@property (strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;

@property(strong,nonatomic)UIImageView *line;




@end

@implementation DMErWeiMaViewController

-(void)viewWillAppear:(BOOL)animated
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusDenied)
        
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"无法访问通讯录" message:@"请到“设置->隐私->相机”中将toon设置为允许访问相机！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alert show];
        
    }else
        
    {
        
        [self setupCamera];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    [self AddLeftImageBtn:[UIImage imageNamed:@"fanhui_03 2"]target:self action:@selector(GoBack)];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initNav];
    [self initOpaqueView];
    [self initBackView];
    
}

-(void)initNav
{
    self.navigationItem.title=@"二维码";
    
}

-(void)initOpaqueView
{   backView=[[UIView alloc]initWithFrame:CGRectMake(leftright, top, Size, Size)];
    UIView *topView=[[UIView alloc]initWithFrame:CGRectMake(leftright+5, 0, backView.frame.size.width-10, top+7)];
    topView.backgroundColor=LIGHT_OPAQUE_BLACK_COLOR;
    [self.view addSubview:topView];
    
    UIView *downView=[[UIView alloc]initWithFrame:CGRectMake(leftright+5, CGRectGetMaxY(backView.frame)-6, backView.frame.size.width-10, 800)];
    downView.backgroundColor=LIGHT_OPAQUE_BLACK_COLOR;
    [self.view addSubview:downView];
    
    UIView *leftView=[[UIView alloc]initWithFrame:CGRectMake(0,0,leftright+5, KHeight)];
    leftView.backgroundColor=LIGHT_OPAQUE_BLACK_COLOR;
    [self.view addSubview:leftView];
    
    UIView *rightView=[[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(backView.frame)-5,0,leftright+5, KHeight)];
    rightView.backgroundColor=LIGHT_OPAQUE_BLACK_COLOR;
    [self.view addSubview:rightView];
    
    
//    topView.backgroundColor = [UIColor redColor];
//    downView.backgroundColor = [UIColor blueColor];
//    leftView.backgroundColor = [UIColor magentaColor];
//    rightView.backgroundColor = [UIColor yellowColor];
}
-(void)initBackView
{
  
    [self.view addSubview:backView];
    
    UIImageView *topImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Size, 28)];
    topImage.image=[UIImage imageNamed:@"newbarcode_scan_box_top"];
    [backView addSubview:topImage];
    
    UIImageView *midImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 28, Size, Size-28*2)];
    midImage.image=[UIImage imageNamed:@"newbarcode_scan_box_mid"];
    [backView addSubview:midImage];
    
    UIImageView *bottomIamge=[[UIImageView alloc]initWithFrame:CGRectMake(0, Size-28, Size, 28)];
    bottomIamge.image=[UIImage imageNamed:@"newbarcode_scan_box_bottom"];
    [backView addSubview:bottomIamge];
    
    
    
    self.line=[[UIImageView alloc]initWithFrame:CGRectMake(5, 0, Size-10, 10)];
    
    self.line.image=[UIImage imageNamed:@"newbarcode_scan_line"];
    
    [backView addSubview:self.line];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:.04 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    
}

-(void)setupCamera
{
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if(_device == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"未检测到相机" message:@"请检查相机设备是否正常" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alert show];
        
        return ;
        
    }
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    _output = [[AVCaptureMetadataOutput alloc]init];
    
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //限制扫描区域（上左下右）
    
    [ _output setRectOfInterest : CGRectMake (( KHeight/2-Size/2) / KHeight ,( Width/2-Size/2 )/ Width , Size /KHeight , Size / Width)];
    
    _session = [[AVCaptureSession alloc]init];
    
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:self.input])
    {
        
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
        
    }
    // 条码类型AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    // Preview
    
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    //_preview.frame =CGRectMake(leftright,top,Size,Size);
    
    _preview.frame =CGRectMake(0,0,Width,KHeight);
    
    
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    
    [_session startRunning];
    
    
}


-(void)animation1
{
    self.line.frame=CGRectMake(5, 2*num, Size-10, 10);
    if (2*num>=Size-10-10) {
        num=0;
    }
    num++;
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate

- ( void )captureOutput:( AVCaptureOutput *)captureOutput didOutputMetadataObjects:( NSArray *)metadataObjects fromConnection:( AVCaptureConnection *)connection

{
 
    if ([metadataObjects count ] > 0 )
        
    {
        
        // 停止扫描
        
        [ _session stopRunning ];
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        
        _stringValue = metadataObject. stringValue ;
        
    }

    //
    UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@"信息" message:_stringValue delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alt show];
    //
    [self.session stopRunning];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 2004) {
        [self.navigationController popViewControllerAnimated:YES];
    }else
    {
    if (buttonIndex == 1) {

        [timer invalidate];
        timer=nil;
        
              [AFDownManager POST:_stringValue parameters:nil success:^(id responseObject) {
            
//            NSLog(@"==== %@",responseObject);
            if (responseObject != [NSNull null]&&[responseObject[@"data"]count] !=0) {
          if([responseObject[@"data"][@"id"]length] !=0)
          {
//                [self createTableView];
//                [self downloadData:responseObject[@"data"][@"id"]];
              DMOrderDetail *ordertail = [[DMOrderDetail alloc] init];
              
              ordertail.urls = responseObject[@"data"][@"id"];
              
              ordertail.ident = @"YES";
              
              [self.navigationController pushViewController:ordertail animated:NO];
          }
            }else
            {
                UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@"提示" message:responseObject[@"desc"] delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
                alt.tag = 2004;
                [alt show];
            }
           
        } failure:^(NSError *error) {
            UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@"提示" message:@"二维码信息错误" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
            alt.tag = 2004;
            [alt show];
        }];
        
        
    }else
    {
        [_session startRunning];
    }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


